import { createRouter, createWebHistory } from 'vue-router'
import store from '@/store'

const routes = [
  {
    path: "/",
    component: () => import("@/views/Layout"),
    children: [
      {
        path: "/",
        component: () => import("@/views/home"),
      },
      {
        path: "/member/checkout",
        component: () => import("@/views/member/pay/checkout"),
      },
    ]
  },
  {
    path: "/login",
    component: () => import("@/views/login"),
  },
  {
    path: "/login/callback",
    component: () => import('@/views/login/callback'),
  }
]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})

// 前置导航守卫
router.beforeEach((to, from, next) => {
  // 需要登录的路由:地址是以/member开头
  const { profile } = store.state.user
  if (!profile.token && to.path.startsWith("/member")) {
    return next("/login?redirectUrl=" + encodeURIComponent(to.fullPath))
  }
  next()
})

export default router
